package com.xl.xlserver.mode.login;

import com.alibaba.fastjson.JSONObject;
import com.xl.xlserver.GameUtilEntity.Play;
import com.xl.xlserver.GameUtilEntity.ScokectMessger;
import com.xl.xlserver.gameServer.LobbyManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.util.Map;


public class InitMode {

    Logger logger = LoggerFactory.getLogger(InitMode.class);
    private static InitMode MODE = new InitMode();

    public static InitMode getInitMode(){
        return  MODE;
    }
    /**
     * 添加客户端连接
     */
    public  void addContetion(ChannelHandlerContext ctx){
       String channelId =  ctx.channel().id().toString();
        //添加客户端通道
        if (LobbyManager.gateManager.get(channelId) == null){
            LobbyManager.getInstance().addChannel(channelId,ctx);

        }

    }
    /**
     * 移除客户端
     */
    public  void removeContetion(ChannelHandlerContext ctx){
        String channelId =  ctx.channel().id().toString();
        //移除
        LobbyManager.getInstance().removeChannel(channelId,ctx);

    }

    /**
     * 向客户端发送数据
     * @param message
     */
    public void  SendMessage(ChannelHandlerContext ctx,String message){
     if (ctx == null || ctx.channel().isActive()){
         ctx.write(message);
         ctx.flush();
     }
    }

    /**
     *  添加游戏角色
     */
    public void addPlay(ChannelHandlerContext ctx, ScokectMessger manger){
      Play play =  JSONObject.parseObject(manger.getData(),Play.class);
        InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        int post = ipSocket.getPort();
        LobbyManager.getInstance().addPlayer(clientIp+":"+post,ctx ,play);
        System.out.println("添加了角色"+clientIp+":"+post);
    }

    /**
     * 向多位客户端发送信息
     * @param
     */
    public void  SendaLLMessage(ChannelHandlerContext ctx,int mapId,String data){
      String chnnelId = ctx.channel().id().toString();
        ByteBuf resp = Unpooled.buffer();
        resp.writeBytes(data.getBytes());
        resp.retain(1);
        if (LobbyManager.playerManager.size() > 0) {
            for (Map.Entry<String, Play> entry : LobbyManager.playerManager.entrySet()) {
                try {
                    if (mapId == entry.getValue().getMapCode()) {
                        String manager =  LobbyManager.session.get(entry.getValue().getPlayName());
                        Channel chiect = LobbyManager.gateManager.get(manager);
                        chiect.writeAndFlush(resp);
                    }
                }catch (Exception e){
                    System.out.println(e);
                }
            }
        }
    }


}
